import { useProject } from "../../hooks/useProjects";
import { useMemo } from "react";
import {
  useSetUrlQueryParam,
  useUrlQueryParam,
} from "../../hooks/useUrlQueryParam";

// 项目列表搜索的参数
export const useProjectsSearchParams = () => {
  const [params, setParams] = useUrlQueryParam(["name", "personId"]);
  return [
    useMemo(
      () => ({ ...params, personId: Number(params.personId) || undefined }),
      [params]
    ),
    setParams,
  ] as const;
};
export const useProjectsQueryKey = () => {
  const [queryKey] = useProjectsSearchParams();
  return ["projects", queryKey];
};
export const useProjectModal = () => {
  const [{ projectCreation }, setProjectCreation] = useUrlQueryParam([
    "projectCreation",
  ]);
  const [{ projectEditionId }, setProjectEditionId] = useUrlQueryParam([
    "projectEditionId",
  ]);
  const setSearchParams = useSetUrlQueryParam();

  const { data: projectToBeEdited, isLoading } = useProject(
    Number(projectEditionId)
  );
  const openProjectModal = () => setProjectCreation({ projectCreation: true });

  const closeProjectModal = () =>
    setSearchParams({
      projectCreation: "",
      projectEditionId: "",
    });

  const editProject = (id: number) =>
    setProjectEditionId({ projectEditionId: id });

  return {
    projectModalVisible:
      projectCreation === "true" || Boolean(projectEditionId),
    openProjectModal,
    closeProjectModal,
    projectToBeEdited,
    isLoading,
    editProject,
  };
};
